/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ohos.openharmony_qsvideoplayer.slice;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.ohos.openharmony_qsvideoplayer.ResourceTable;
import com.ohos.openharmony_qsvideoplayer.danmaku.AbilityManager;
import com.ohos.openharmony_qsvideoplayer.danmaku.BiliDanmukuParser;
import master.flame.danmaku.controller.IDanmakuView;
import master.flame.danmaku.danmaku.loader.ILoader;
import master.flame.danmaku.danmaku.loader.IllegalDataException;
import master.flame.danmaku.danmaku.loader.android.DanmakuLoaderFactory;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.DanmakuTimer;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.IDisplayer;
import master.flame.danmaku.danmaku.model.android.BaseCacheStuffer;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.model.android.SimpleTextCacheStuffer;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import master.flame.danmaku.danmaku.parser.IDataSource;
import master.flame.danmaku.danmaku.util.SystemClock;
import master.flame.danmaku.ui.widget.DanmakuView;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.MemoryInfo;
import ohos.aafwk.ability.SystemMemoryInfo;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Button;
import ohos.agp.components.Text;
import ohos.agp.components.Component;
import ohos.agp.components.ScrollView;
import ohos.agp.components.TextField;
import ohos.agp.utils.Color;
import ohos.agp.components.LayoutScatter;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.Window;
import ohos.agp.window.service.WindowManager;
import ohos.app.IAbilityManager;
import ohos.bundle.IBundleManager;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import org.song.videoplayer.DemoQSVideoView;
import org.song.videoplayer.QSVideo;
import org.song.videoplayer.Util;
import org.song.videoplayer.IVideoPlayer;
import org.song.videoplayer.PlayListener;
import org.song.videoplayer.floatwindow.FloatParams;
import org.song.videoplayer.media.BaseMedia;
import org.song.videoplayer.media.HarmonyMedia;

import static ohos.media.codec.CodecDescriptionList.getSupportedMimes;


public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {

    private String mp4 = "https://mos-vod-drcn.dbankcdn.cn/P_VT/video_injection/A91343E9D/v3/9AB0A7921049102362779584128/MP4Mix_H.264_1920x1080_6000_HEAAC1_PVC_NoCut.mp4";
    private String _mp4 = "https://media.w3.org/2010/05/sintel/trailer.mp4";
    private String m3u8 = "http://ivi.bupt.edu.cn/hls/cctv6hd.m3u8";

    private String url;
    private Class<? extends BaseMedia> decodeMedia;
    private DemoQSVideoView demoVideoView;
    private ScrollView scrollView;
    private Text descriptionText;
    private Button systemButton, exoButton, ijkButton, ijkExoButton, urlButton, m3u8Button, muteButton, zoomButton, videoListButton, floatingButton, systemFloatingButton, danmakuButton, sendDanmakuButton, destroyButton;

    private IDanmakuView mDanmakuView;
    private DanmakuContext mContext;
    private BaseDanmakuParser mParser;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        WindowManager.getInstance().getTopWindow().get().setTransparent(true);

        findComponentById(ResourceTable.Id_btn_url).setLongClickedListener(new Component.LongClickedListener() {
            @Override
            public void onLongClicked(Component component) {
                changeUrl();
            }
        });

        descriptionText = (Text) findComponentById(ResourceTable.Id_tv_title);
        descriptionText.setText("QSVideoPlayer \ngithub.com/tohodog");

        scrollView = (ScrollView) findComponentById(ResourceTable.Id_scroll_view);
        demoVideoView = (DemoQSVideoView) findComponentById(ResourceTable.Id_qs);
        demoVideoView.bindAbilitySlice(this);
        demoVideoView.setUIWithStateAndMode();
        demoVideoView.getCoverImageView().setImageAndDecodeBounds(ResourceTable.Media_cover);

//        demoVideoView.setLayoutConfig(new DependentLayout.LayoutConfig(-1, getResourceManager().getDeviceCapability().width * 9 / 16));
        //进入全屏的模式 0横屏 1竖屏 2传感器自动横竖屏 3根据视频比例自动确定横竖屏      -1什么都不做
        demoVideoView.enterFullMode = 3;
        //是否非全屏下也可以手势调节进度
        demoVideoView.isWindowGesture = true;
        initDamukuView();
        initButtonItem();
        demoVideoView.setPlayListener(new PlayListener() {

            int mode;

            @Override
            public void onStatus(int status) {//播放状态
                if (status == IVideoPlayer.STATE_AUTO_COMPLETE)
                    demoVideoView.quitWindowFullscreen();//播放完成退出全屏
            }


            @Override//全屏/普通/浮窗
            public void onMode(int mode) {
                this.mode = mode;
            }

            @Override
            public void onEvent(int what, Integer... extra) {
                if (what == org.song.videoplayer.DemoQSVideoView.EVENT_CONTROL_VIEW && mode == IVideoPlayer.MODE_WINDOW_NORMAL) {
                    Util.CLEAR_FULL(MainAbilitySlice.this);
                }
//                //系统浮窗点击退出退出activity
//                if (what == DemoQSVideoView.EVENT_CLICK_VIEW
//                        && extra[0] == R.id.help_float_close)
//                    if (demoVideoView.isSystemFloatMode())
//                        terminate();
            }

        });
        play(mp4, HarmonyMedia.class);
    }

    private void play(String url, Class<? extends BaseMedia> decodeMedia) {
        demoVideoView.release();
        demoVideoView.setDecodeMedia(decodeMedia);

        demoVideoView.setUp(
                QSVideo.Build(url).title("这是标清标题").definition("标清").resolution("标清 720P").build(),
                QSVideo.Build(url).title("这是高清标题").definition("高清").resolution("高清 1080P").build(),
                QSVideo.Build(url).title("这是2K标题").definition("2K").resolution("超高清 2K").build(),
                QSVideo.Build(url).title("这是4K标题").definition("4K").resolution("极致 4K").build()

        );
//        demoVideoView.setUp(url, "这是一个标题");
        //demoVideoView.seekTo(12000);
        demoVideoView.openCache();//缓存配置见最后,缓存框架可能会出错,
        demoVideoView.play();
        this.url = url;
        this.decodeMedia = decodeMedia;

    }

    @Override
    public void onActive() {
        super.onActive();
        System.out.println("===onActive===>");
        if (playFlag) {
            demoVideoView.play();
        }
        handler.removeTask(runnable);
        if (position > 0) {
            demoVideoView.seekTo(position);
            position = 0;
        }
//        if (demoVideoView != null) {
//            if (getDisplayOrientation() == 0) {//横屏
//                demoVideoView.enterWindowFullscreen();
//            } else {
//                demoVideoView.quitWindowFullscreen();
//            }
//        }

        if (mDanmakuView != null && mDanmakuView.isPrepared() && mDanmakuView.isPaused()) {
            mDanmakuView.resume();
        }
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    public void changeUrl() {
        CommonDialog commonDialog = new CommonDialog(this);
        Component component = LayoutScatter.getInstance(getContext())
                .parse(ResourceTable.Layout_dialog_custom_layout, null, false);
        commonDialog.setContentCustomComponent(component);
        TextField textField = (TextField) component.findComponentById(ResourceTable.Id_textfield);
        textField.setText(_mp4);
        commonDialog.show();

        Button webButton = (Button) component.findComponentById(ResourceTable.Id_web);
        Button localButton = (Button) component.findComponentById(ResourceTable.Id_local);

        webButton.setText("网络视频");
        localButton.setText("本地视频");

        webButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                commonDialog.hide();
                commonDialog.destroy();
                play(textField.getText(), HarmonyMedia.class);
                textField.setText(textField.getText());
                setTitle("网络视频： " + textField.getText());
            }
        });

        localButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                commonDialog.hide();
                commonDialog.destroy();
                new ToastDialog(getContext()).setText("Waiting...").show();
            }
        });

    }

    //设置数据源
    private BaseDanmakuParser createParser(InputStream stream) {

        if (stream == null) {
            return new BaseDanmakuParser() {

                @Override
                protected Danmakus parse() {
                    return new Danmakus();
                }
            };
        }

        ILoader loader = DanmakuLoaderFactory.create(DanmakuLoaderFactory.TAG_BILI);

        try {
            loader.load(stream);
        } catch (IllegalDataException e) {
            e.printStackTrace();
        }
        BaseDanmakuParser parser = new BiliDanmukuParser();
        IDataSource<?> dataSource = loader.getDataSource();
        parser.load(dataSource);
        return parser;

    }

    public void initDamukuView() {
        WindowManager windowManager = WindowManager.getInstance();
        Window window = windowManager.getTopWindow().get();
        WindowManager.LayoutConfig layoutConfig = new WindowManager.LayoutConfig();
        layoutConfig.flags = WindowManager.LayoutConfig.MARK_ALLOW_LAYOUT_COVER_SCREEN;
        layoutConfig.flags = layoutConfig.flags | WindowManager.LayoutConfig.MARK_FULL_SCREEN;
        layoutConfig.windowBrightness = 1.0f;
        window.setLayoutConfig(layoutConfig);
        window.addFlags(WindowManager.LayoutConfig.MARK_LAYOUT_ATTACHED_IN_DECOR);
        window.addFlags(WindowManager.LayoutConfig.MARK_LAYOUT_INSET_DECOR);

        System.out.println(" height ====+++++++++============= : " + layoutConfig.height);
        System.out.println(" width  ====+++++++++============= : " + layoutConfig.width);
        window.setBackgroundColor(new RgbColor(0xB7B208));

        DanmakuView danmakuView = (DanmakuView) findComponentById(ResourceTable.Id_sv_danmaku);
        danmakuView.addDrawTask(null);
        danmakuView.setLayoutRefreshedListener(null);

        // 设置最大显示行数
        HashMap<Integer, Integer> maxLinesPair = new HashMap<Integer, Integer>();
        maxLinesPair.put(BaseDanmaku.TYPE_SCROLL_RL, 5); // 滚动弹幕最大显示5行
        // 设置是否禁止重叠
        HashMap<Integer, Boolean> overlappingEnablePair = new HashMap<Integer, Boolean>();
        overlappingEnablePair.put(BaseDanmaku.TYPE_SCROLL_RL, true);
        overlappingEnablePair.put(BaseDanmaku.TYPE_FIX_TOP, true);

        mDanmakuView = (IDanmakuView) findComponentById(ResourceTable.Id_sv_danmaku);
        mContext = DanmakuContext.create();
        mContext.setDanmakuStyle(IDisplayer.DANMAKU_STYLE_STROKEN, 3)   //设置描边样式
                .setDuplicateMergingEnabled(false)  //设置不合并相同内容弹幕
                .setScrollSpeedFactor(0.9f)         //设置弹幕滚动速度缩放比例，越大速度越慢
                .setScaleTextSize(1.2f)             //设置字体缩放比例
//                .setCacheStuffer(new SpannedCacheStuffer(), mCacheStufferAdapter) // 图文混排使用SpannedCacheStuffer
                .setCacheStuffer(new SimpleTextCacheStuffer(), mCacheStufferAdapter)        //===========这里修改为使用SimpleTextCacheStuffer
//        .setCacheStuffer(new BackgroundCacheStuffer())  // 绘制背景使用BackgroundCacheStuffer
                .setMaximumLines(maxLinesPair)              //设置最大行数策略
                .preventOverlapping(overlappingEnablePair)  //设置禁止重叠策略
                .setDanmakuMargin(40);

        if (mDanmakuView != null) {

            InputStream stream = null;
            try {
                stream = this.getResourceManager().getRawFileEntry("resources/rawfile/comments.xml").openRawFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

            mParser = createParser(stream);

            mDanmakuView.setCallback(new master.flame.danmaku.controller.DrawHandler.Callback() {
                @Override
                public void updateTimer(DanmakuTimer timer) {
                }

                @Override
                public void drawingFinished() {

                }

                @Override
                public void danmakuShown(BaseDanmaku danmaku) {
//                    Log.d("DFM", "danmakuShown(): text=" + danmaku.text);
                }

                @Override
                public void prepared() {
                    mDanmakuView.start();
                }
            });
            mDanmakuView.setOnDanmakuClickListener(new IDanmakuView.OnDanmakuClickListener() {

                @Override
                public boolean onDanmakuClick(IDanmakus danmakus) {
//                    Log.d("DFM", "onDanmakuClick: danmakus size:" + danmakus.size());
                    BaseDanmaku latest = danmakus.last();
                    if (null != latest) {
//                        Log.d("DFM", "onDanmakuClick: text of latest danmaku:" + latest.text);
                        return true;
                    }
                    return false;
                }

                @Override
                public boolean onDanmakuLongClick(IDanmakus danmakus) {
                    return false;
                }

                @Override
                public boolean onViewClick(IDanmakuView view) {
//                    mMediaController.setVisibility(View.VISIBLE);
                    return false;
                }
            });
            mDanmakuView.prepare(mParser, mContext);
            mDanmakuView.showFPS(true);
            mDanmakuView.enableDanmakuDrawingCache(true);
            mDanmakuView.hide();
        }

    }

    public void initButtonItem() {
        systemButton = (Button) findComponentById(ResourceTable.Id_system);
        exoButton = (Button) findComponentById(ResourceTable.Id_exo);
        ijkButton = (Button) findComponentById(ResourceTable.Id_ijk_ffemepg);
        ijkExoButton = (Button) findComponentById(ResourceTable.Id_ijk_exo);
        urlButton = (Button) findComponentById(ResourceTable.Id_btn_url);
        m3u8Button = (Button) findComponentById(ResourceTable.Id_m3u8);
        muteButton = (Button) findComponentById(ResourceTable.Id_mute);
        zoomButton = (Button) findComponentById(ResourceTable.Id_zoom);
        videoListButton = (Button) findComponentById(ResourceTable.Id_video_list);
        floatingButton = (Button) findComponentById(ResourceTable.Id_floating_windows);
        systemFloatingButton = (Button) findComponentById(ResourceTable.Id_system_floating);
        danmakuButton = (Button) findComponentById(ResourceTable.Id_display_danmaku);
        sendDanmakuButton = (Button) findComponentById(ResourceTable.Id_send_danmaku);
        destroyButton = (Button) findComponentById(ResourceTable.Id_button);

        systemButton.setClickedListener(this);
        exoButton.setClickedListener(this);
        ijkButton.setClickedListener(this);
        ijkExoButton.setClickedListener(this);
        urlButton.setClickedListener(this);
        m3u8Button.setClickedListener(this);
        muteButton.setClickedListener(this);
        zoomButton.setClickedListener(this);
        videoListButton.setClickedListener(this);
        floatingButton.setClickedListener(this);
        systemFloatingButton.setClickedListener(this);
        danmakuButton.setClickedListener(this);
        sendDanmakuButton.setClickedListener(this);
        destroyButton.setClickedListener(this);

    }

    private BaseCacheStuffer.Proxy mCacheStufferAdapter = new BaseCacheStuffer.Proxy() {

//        private Drawable mDrawable;

        @Override
        public void prepareDrawing(final BaseDanmaku danmaku, boolean fromWorkerThread) {
//            if (danmaku.text instanceof Spanned) { // 根据你的条件检查是否需要需要更新弹幕
//                // FIXME 这里只是简单启个线程来加载远程url图片，请使用你自己的异步线程池，最好加上你的缓存池
//                new Thread() {
//
//                    @Override
//                    public void run() {
//                        String url = "http://www.bilibili.com/favicon.ico";
//                        InputStream inputStream = null;
//                        Drawable drawable = mDrawable;
//                        if(drawable == null) {
//                            try {
//                                URLConnection urlConnection = new URL(url).openConnection();
//                                inputStream = urlConnection.getInputStream();
//                                drawable = BitmapDrawable.createFromStream(inputStream, "bitmap");
//                                mDrawable = drawable;
//                            } catch (MalformedURLException e) {
//                                e.printStackTrace();
//                            } catch (IOException e) {
//                                e.printStackTrace();
//                            } finally {
//                                IOUtils.closeQuietly(inputStream);
//                            }
//                        }
//                        if (drawable != null) {
//                            drawable.setBounds(0, 0, 100, 100);
//                            SpannableStringBuilder spannable = createSpannable(drawable);
//                            danmaku.text = spannable;
//                            if(mDanmakuView != null) {
//                                mDanmakuView.invalidateDanmaku(danmaku, false);
//                            }
//                            return;
//                        }
//                    }
//                }.start();
//            }
        }

        @Override
        public void releaseResource(BaseDanmaku danmaku) {
            // TODO 重要:清理含有ImageSpan的text中的一些占用内存的资源 例如drawable
        }
    };

    //输出系统内存信息
    public static void printMem() {
        IAbilityManager iAbilityManager = new AbilityManager();
        SystemMemoryInfo outInfo = new SystemMemoryInfo();
        iAbilityManager.getSystemMemoryInfo(outInfo);

        MemoryInfo memoryInfo = new MemoryInfo();

        System.out.println("===========================\n");
        System.out.println("可用内存" + outInfo.getAvailSysMem());
        System.out.println("系统内存" + outInfo.getTotalSysMem());
        System.out.println("app内存" + memoryInfo.getArkPrivateDirty());
        System.out.println("===========================\n");
    }


    private String[] arr = {"适应", "填充", "原尺寸", "拉伸", "16:9", "4:3"};
    private int mode;
    private boolean mute;

    private float rate = 1.f;

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_system:
                play(url, HarmonyMedia.class);
                setTitle("系统硬解");
                break;
            case ResourceTable.Id_exo:
//                play(url, ExoMedia.class);
                setTitle("exo解码");
                break;
            case ResourceTable.Id_ijk_ffemepg:
//                play(url, IjkMedia.class);
                setTitle("ijk_ffmepg解码");
                break;
            case ResourceTable.Id_ijk_exo:
//                play(url, IjkExoMedia.class);
                setTitle("ijk_exo解码");
                break;
            case ResourceTable.Id_btn_url:
                play(mp4, decodeMedia);
                setTitle("网络视频： " + mp4);
                break;
            case ResourceTable.Id_m3u8:
                List<String> mimes = getSupportedMimes();
                for (int i = 0; i < mimes.size(); i++) {
                    System.out.println("===mimes===>" + mimes.get(i));
                }
                play(m3u8, decodeMedia);
                setTitle("m3u8直播: " + m3u8);
                break;
            case ResourceTable.Id_mute:
                demoVideoView.setMute(mute = !mute);
                ((Button) component).setText(mute ? "静音 ON" : "静音 OFF");
                break;
            case ResourceTable.Id_zoom:
                demoVideoView.setAspectRatio(++mode > 5 ? mode = 0 : mode);
                ((Button) component).setText(arr[mode]);
                break;
            case ResourceTable.Id_video_list:
//                Operation operation = new Intent.OperationBuilder().withAction("action.list").build();
//                intent.setOperation(operation);
//                startAbility(intent);

                Intent intent = new Intent();
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName("com.ohos.openharmony_qsvideoplayer")
                        .withAbilityName("com.ohos.openharmony_qsvideoplayer.ListVideoAbility")
                        .build();
                intent.setOperation(operation);
                startAbility(intent);

                new ToastDialog(getContext()).setText("Turn to video list page.").show();
                break;
            case ResourceTable.Id_floating_windows:
                if (demoVideoView.getCurrentMode() == IVideoPlayer.MODE_WINDOW_FLOAT_SYS) {
                    return;
                }
                enterFloat(false);
                ((Button) component).setText(demoVideoView.isWindowFloatMode() ? "退出浮窗" : "界面内浮窗");
                break;
            case ResourceTable.Id_system_floating:
                if (demoVideoView.getCurrentMode() == IVideoPlayer.MODE_WINDOW_FLOAT_ACT) {
                    return;
                }
                enterFloat(true);
                ((Button) component).setText(demoVideoView.isWindowFloatMode() ? "退出浮窗" : "系统浮窗");
                break;
            case ResourceTable.Id_display_danmaku:
                if (mDanmakuView.isShown()) {
                    mDanmakuView.hide();
                    setTitle("隐藏弹幕");
                } else {
                    mDanmakuView.show();
                    setTitle("显示弹幕");
                }

                break;
            case ResourceTable.Id_send_danmaku:
                addDanmaku(false);
                setTitle("发送弹幕");
                break;

            case ResourceTable.Id_button:
                demoVideoView.release();
                setTitle("销毁");
                break;
            case ResourceTable.Id_speed:
                rate += 0.25f;
                if (rate > 2)
                    rate = 0.25f;

                if (!demoVideoView.setSpeed(rate)) {
                    new ToastDialog(getContext()).setText("该解码器不支持").show();
                    rate = 1f;
                }
                ((Button) component).setText("倍速 X" + rate);
                break;
        }

    }

    @Override
    protected void onBackPressed() {
        if (demoVideoView.onBackPressed()) {
            if (demoVideoView.isSystemFloatMode()) {
//                    moveTaskToBack(true);
            }
        } else {
            super.onBackPressed();
        }
    }

    //进入浮窗
    private void enterFloat(boolean isSystemFloat) {
        FloatParams floatParams = demoVideoView.getFloatParams();
        if (floatParams == null) {
            floatParams = new FloatParams();
            floatParams.x = 0;
            floatParams.y = 0;
            floatParams.w = getResourceManager().getDeviceCapability().width * 3 / 4;
            floatParams.h = floatParams.w * 9 / 16;
            floatParams.round = 30;
            floatParams.fade = 0.8f;
            floatParams.canMove = true;
            floatParams.canCross = false;
        }
        floatParams.systemFloat = isSystemFloat;

        if (demoVideoView.isWindowFloatMode())
            demoVideoView.quitWindowFloat();
        else {
            demoVideoView.enterWindowFloat(floatParams);
            if (verifyCallingPermission("ohos.permission.SYSTEM_FLOAT_WINDOW") != IBundleManager.PERMISSION_GRANTED) {
                // 调用者无权限，做错误处理
                new ToastDialog(getContext()).setText("没有系统浮窗权限").show();
            }
        }
        if (demoVideoView.isSystemFloatMode())
            onBackPressed();
    }

    public void setTitle(String title) {
        ((Text) findComponentById(ResourceTable.Id_tv_title)).setText(title);
    }


    Timer timer = new Timer();

    class AsyncAddTask extends TimerTask {

        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                addDanmaku(true);
                SystemClock.sleep(20);
            }
        }
    }


    private void addDanmaku(boolean islive) {
        BaseDanmaku danmaku = mContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
        if (danmaku == null || mDanmakuView == null) {
            return;
        }

        danmaku.text = "弹幕发送测试-> 系统时间：" + System.nanoTime();
        danmaku.padding = 5;
        danmaku.priority = 0;  // 可能会被各种过滤器过滤并隐藏显示
        danmaku.isLive = islive;
        danmaku.setTime(mDanmakuView.getCurrentTime() + 1200);
        danmaku.textSize = 25f * (mParser.getDisplayer().getDensity() - 0.6f);
        danmaku.textColor = Color.RED.getValue();
        danmaku.textShadowColor = Color.WHITE.getValue();

        danmaku.borderColor = Color.GREEN.getValue();
        System.out.println("addDanmaku: " + danmaku.text);
        mDanmakuView.addDanmaku(danmaku);
    }

    //=======================以下生命周期控制=======================

    private boolean playFlag;//记录退出时播放状态 回来的时候继续播放
    private int position;//记录销毁时的进度 回来继续该进度播放
    private EventHandler handler = new EventHandler(EventRunner.getMainEventRunner());


    @Override
    protected void onBackground() {
        super.onBackground();
        if (demoVideoView.isSystemFloatMode()) {
            return;
        }
        //暂停
        playFlag = demoVideoView.isPlaying();
        demoVideoView.pause();
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        if (demoVideoView.isSystemFloatMode())
            return;
        //进入后台不马上销毁,延时15秒
        handler.postTask(runnable, 1000 * 15);

        if (mDanmakuView != null && mDanmakuView.isPrepared()) {
            mDanmakuView.pause();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        System.out.println("===onStop===>");
        if (demoVideoView.isSystemFloatMode()) {
            demoVideoView.quitWindowFloat();
        }
        demoVideoView.release();
        handler.removeTask(runnable);

//        if (mDanmakuView != null) {
//            // dont forget release!
//            mDanmakuView.release();
//            mDanmakuView = null;
//        }
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (demoVideoView.getCurrentState() != IVideoPlayer.STATE_AUTO_COMPLETE)
                position = demoVideoView.getPosition();
            demoVideoView.release();
        }
    };
}
